package com.kpmg.datalake.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * 设置响应头信息
 * @author Tony
 */
public class ResponseUtils {
	
	private ResponseUtils() {}

	private static final Logger logger = LoggerFactory.getLogger(ResponseUtils.class);
	

	/**
	 * 设置CSV文件下载
	 * @param fileName
	 * @param request
	 * @param response
	 */
	public static void setCsvDownloadResponseHeader(String fileName, HttpServletRequest request, HttpServletResponse response) {
		String type = "application/csv;charset=utf-8";
		setDownloadResponseHeader(type, fileName, request, response);
	}

	/**
	 * 设置Zip文件下载
	 * @param fileName
	 * @param request
	 * @param response
	 */
	public static void setZipDownloadResponseHeader(String fileName, HttpServletRequest request, HttpServletResponse response) {
		String type = "application/octet-stream";
		setDownloadResponseHeader(type, fileName, request, response);
	}
	
	/**
	 * 设置Excel文件下载
	 * @param fileName
	 * @param request
	 * @param response
	 */
	public static void setExcelDownloadResponseHeader(String fileName, HttpServletRequest request, HttpServletResponse response) {
		String type = "application/vnd.ms-excel";
		setDownloadResponseHeader(type, fileName, request, response);
	}

	/**
	 * 设置统一的文件下载头信息
	 * @param type type
	 * @param fileName fileName
	 * @param request request
	 * @param response response
	 */
	private static void setDownloadResponseHeader(String type, String fileName, HttpServletRequest request, HttpServletResponse response) {
		String encoding = "UTF-8";
		response.setContentType(type);
		response.setCharacterEncoding(encoding);

		String browserType = BrowserUtil.getBrowserName(request);
		try {
			if (BrowserUtil.BrowserTypeEnum.FIREFOX.getBrowserName().equals(browserType)) {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			}else {
				fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("%28", "\\(").replaceAll("%29", "\\)");
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		} catch (Exception e) {
			logger.error("文件下载请求头设置失败：" + e.getMessage(), e);
		}
	}
	

}
